<script setup lang="ts">
import { ref, inject } from 'vue'
import { useRouter } from 'vue-router'
// import { showLoadingToast, closeToast } from 'vant'
import { login } from '@/api/user'
import { setToken } from '@/utils/auth'
import logo from '@/assets/shopping-icon.svg'


const $toast: any = inject('$toast', () => {})
const router = useRouter()

const username = ref('')
const password = ref('')
const checked = ref(false)
const loading = ref(false)

const onSubmit = async (formData: any) => {
  // showLoadingToast({
  //   forbidClick: true,
  //   message: '加载中...',
  //   loadingType: 'spinner',
  // })
  loading.value = true
  await login({ phone: formData.username, password: formData.password })
    .then(({ data }) => {
      setToken(data.refresh_token)
      localStorage.setItem('token', data.token)
      router.push('/home')
    })
    .catch(({ message }) => {
      $toast(message || '登录失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 登陆页中避免100vh造成的页面滑动
</script>

<template>
  <div>
    <div class="head-img">
      <van-image
        width="30vmax"
        fit="contain"
        :src="logo"
      />
    </div>
    <van-form @submit="onSubmit" class="login-form">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 60px 30px 0;">
        <van-button round block :loading="loading" type="primary" loading-text="登录中..." native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
    <div class="validate-bar">
      <p>
        <a>忘记密码</a>
        <a @click="$router.push('/register')">还没有账号？点击此处注册</a>
      </p>
      <!-- <van-checkbox v-model="checked">
        我已阅读并同意xxxx协议
      </van-checkbox> -->
    </div>
  </div>
</template>

<style lang="scss" scoped>
.head-img {
  // margin-top: 2vh;
  text-align: center;
}
.validate-bar {
  margin: 0 30px;
  p {
    display: flex;
    justify-content: space-between;
  }
}
.login-form {
  margin-top: 2vh;
}
</style>